import { Component, OnInit, Input } from '@angular/core';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { EventService } from '../../shared/service/event.service';

@Component({
  selector: 'app-submit-form',
  templateUrl: './submit-form.component.html',
  styleUrls: ['./submit-form.component.scss'],
})
export class SubmitFormComponent implements OnInit {

  @Input() tagData: any;
  values: any; // textarea输入的值
  paramName: any;
  text = {}; // 传入的所有参数
  endCheck: any; // 结束原因选择
  phoneNumber = localStorage.getItem("loginAccount"); // 电话号码
  password: any; // 验证码
  time = -1;

  constructor(
    private http: HttpService,
    private eventService: EventService,
    private appGlobalService: AppGlobalService
  ) { }

  ngOnInit() {
    // if (this.tagData) {
    //   this.tagData.data.data.forEach(element => {
    //     if (element.formType === "listCheckbox") {
    //       element.forEach(data=>{
    //         let listCheckboxStr='';
    //         if(data.checked){
    //           if(listCheckboxStr !== ''){
    //             listCheckboxStr=listCheckboxStr + ',' + data.id;
    //           }else{
    //             listCheckboxStr = data.id;
    //           }
    //         }
    //         this.text["listCheckbox"]=listCheckboxStr;
    //       });
    //     }
    //   });
    // }
    if (this.tagData) {
      this.paramName = this.tagData.data.paramName;
      // tslint:disable-next-line:prefer-for-of
      for (let i = 0; i < this.tagData.data.data.length; i++) {
        if (this.tagData.data.data[i].formType === "listCheckbox") {
          let listCheckboxStr = '';
          if (this.tagData.data.data[i].data) {
            // tslint:disable-next-line:prefer-for-of
            for (let j = 0; j < this.tagData.data.data[i].data.length; j++) {
              if (this.tagData.data.data[i].data[j].checked) {
                if (listCheckboxStr !== '') {
                  listCheckboxStr = listCheckboxStr + ',' + this.tagData.data.data[i].data[j].id;
                } else {
                  listCheckboxStr = this.tagData.data.data[i].data[j].id;
                }
                this.saveStorageObj(this.tagData.data.data[i].data[j]);
              }
              // tslint:disable-next-line:no-string-literal
              if (this.tagData.data.data[i].alias) {
                this.text[this.tagData.data.data[i].alias] = listCheckboxStr;
              } else {
                // tslint:disable-next-line:no-string-literal
                this.text["listCheckbox"] = listCheckboxStr;
              }
              this.saveParam();
            }
          }
        }
        if (this.tagData.data.data[i].formType === "textarea") {
          // tslint:disable-next-line:prefer-const
          let textarea = '';
          // tslint:disable-next-line:no-string-literal
          if (this.tagData.data.data[i].alias) {
            this.text[this.tagData.data.data[i].alias] = textarea;
          } else {
            // tslint:disable-next-line:no-string-literal
            this.text["textarea"] = textarea;
          }
          this.saveParam();
        }
      }
    }
    this.eventService.eventEmit.emit("submitTag", this.tagData);
    console.log(this.tagData);
  }

  /** 实时获取输入框值并储存到localstorage */
  getValue(item, event) {
    item.value = this.values;
    // tslint:disable-next-line:no-string-literal
    if (item.alias) {
      this.text[item.alias] = this.values;
    } else {
      this.text["textarea"] = this.values;
    }
    this.saveParam();
    this.eventService.eventEmit.emit("submitTag", this.tagData);
  }

  /** 结束服务选择值 */
  checkEnd(item, check) {
    this.endCheck = check;
    item.value = this.endCheck;
    // tslint:disable-next-line:no-string-literal
    if (item.alias) {
      this.text[item.alias] = this.endCheck;
    } else {
      this.text["radio"] = this.endCheck;
    }
    this.saveParam();
    this.eventService.eventEmit.emit("submitTag", this.tagData);
  }

  /** 结束服务输入值 */
  checkTextarea(item, event) {
    item.value = this.values;
    // tslint:disable-next-line:no-string-literal
    if (item.alias) {
      this.text[item.alias] = this.values;
    } else {
      this.text["radio"] = this.values;
    }
    this.saveParam();
    this.eventService.eventEmit.emit("submitTag", this.tagData);
  }

  /** 邀约看店选择数据 */
  invitationCheck(item, event) {
    const listCheckboxStr = '';
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < item.data.length; i++) {
      if (item.data[i] === event) {
        item.data[i].checked = !item.data[i].checked;
        if (item.data[i].checked) {
          this.saveStorageObj(item.data[i]);
          const arr = JSON.parse(localStorage.getItem('invitationArr'));
          if (arr.length === 4) {
            event.checked = false;
            this.removeStorageObj(item.data[i]);
            this.appGlobalService.showToast('最多只能发送三个' + (item.data[i].pluginId === '3' ? '选址' : '物业' + '信息'), 2000, 'middle');
            break;
          }
        } else {
          this.removeStorageObj(item.data[i]);
        }
      }
    }
    // item.data.forEach(data => {

    // if (data.checked) {
    //   this.saveStorageObj(event);
    //   // if (listCheckboxStr !== '') {
    //   //   listCheckboxStr = listCheckboxStr + ',' + data.id;
    //   // } else {
    //   //   listCheckboxStr = data.id;
    //   // }
    // }
    //});
    item.value = listCheckboxStr;
    // tslint:disable-next-line:no-string-literal
    if (item.alias) {
      this.text[item.alias] = listCheckboxStr;
    } else {
      // tslint:disable-next-line:no-string-literal
      this.text["listCheckbox"] = listCheckboxStr;
    }
    // this.saveParam();
    // this.eventService.eventEmit.emit("submitTag", this.tagData);
  }

  saveStorageObj(obj) {
    if (localStorage.getItem('invitationArr')) {
      const arr = JSON.parse(localStorage.getItem('invitationArr'));
      localStorage.removeItem('invitationArr');
      const len = arr.length - 1;
      if (len > 0) {
        for (let i = 0; i < len; i++) {
          if (obj.id !== arr[i].id) {
            arr.push(obj);
            break;
          }
        }
      } else {
        arr.push(obj);
      }
      localStorage.setItem('invitationArr', JSON.stringify(arr));
    } else {
      const arr = [];
      arr.push(obj);
      const arrStr = JSON.stringify(arr);
      localStorage.setItem('invitationArr', arrStr);
    }
  }

  removeStorageObj(obj) {
    if (localStorage.getItem('invitationArr')) {
      const arr = JSON.parse(localStorage.getItem('invitationArr'));
      localStorage.removeItem('invitationArr');
      const tmpArr = [];
      const len = arr.length;
      for (let i = 0; i < len; i++) {
        if (obj.id !== arr[i].id) {
          tmpArr.push(arr[i]);
        }
      }
      localStorage.setItem('invitationArr', JSON.stringify(tmpArr));
    }
  }

  /** 获取输入的手机号 */
  getPhone(item, event, phone) {
    if (event.detail.value.length >= 11) {
      this.phoneNumber = event.detail.value;
      // tslint:disable-next-line:no-string-literal
      if (item.alias) {
        this.text[item.alias] = this.phoneNumber;
      } else {
        // tslint:disable-next-line:no-string-literal
        this.text["phone"] = this.phoneNumber;
      }
      this.saveParam();
    }
  }

  /** 获取验证码 */
  submitPassword(item) {
    if (!this.phoneNumber) {
      this.appGlobalService.showToast('请输入手机号', 3000, 'top');
      return;
    }
    let a = 0;
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < item.rules.length; i++) {
      if (!RegExp(item.rules[i].rule).test(this.phoneNumber)) {
        this.appGlobalService.showToast(item.rules[i].message, 3000, 'top');
        return;
      } else {
        a = a + 1;
      }
    }
    if (a === item.rules.length) {
      const params = {
        content: {
          mobile: this.phoneNumber
        },
        id: item.codeButton.submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      this.http.post('application/submit', params, (data) => {
        if (data.success) {
          this.appGlobalService.showToast('验证码已发送、请注意查收', 3000, 'top');
          if (data.data) {
            this.password = data.data.mvcode;
          }
          this.time = 90;
          const timer = setInterval(() => {
            this.time = this.time - 1;
            if (this.time === -1) {
              clearInterval(timer);
              this.text = '获取验证码';
            }
          }, 1000);
        }
      });
    };
    if (item.alias) {
      this.text[item.alias] = this.phoneNumber;
    } else {
      this.text["phone"] = this.phoneNumber;
    }
    this.saveParam();
  }

  /** 输入验证码 */
  getPassword(item, str) {
    this.password = str;
    item.value = this.password;
    // tslint:disable-next-line:no-string-literal
    if (item.alias) {
      this.text[item.alias] = this.password;
    } else {
      this.text["input"] = this.password;
    }
    this.saveParam();
  }

  /** 保存参数到本地 */
  saveParam() {
    if (this.paramName) {
      // delete this.checkedService.checked;
      localStorage.setItem(this.paramName, JSON.stringify(this.text));
    }
  }

  /** 销毁本地数据 */
  // tslint:disable-next-line:use-life-cycle-interface
  ngOnDestroy() {
    localStorage.removeItem(this.paramName);
  }

}
